import { useEffect, useState } from "react";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Trash, MinusCircle, PlusCircle } from "lucide-react";
import { CartItem } from "@/types/cart";
import { Decimal } from "decimal.js";
import { cartService } from "@/service/cartService";
import { useNavigate } from "react-router-dom";

export default function Cart() {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const navigate = useNavigate();


  useEffect(() => {
    cartService.getCartItems(1, 100).then(data => setCartItems(data.items));
  }, []);
  
  // 修改商品数量
  const updateQuantity = (id: number, newQuantity: number) => {
    if (newQuantity < 1) return;
    
    setCartItems(prevItems =>
      prevItems.map(item =>
        item.id === id ? { ...item, quantity: newQuantity } : item
      )
    );
  };
  
  // 删除商品
  const removeItem = (id: number) => {
    setCartItems(prevItems => prevItems.filter(item => item.id !== id));
  };
  
  // 计算总价
  const totalPrice = cartItems.reduce(
    (sum, item) => sum.plus(new Decimal(item.price).mul(item.quantity)),
    new Decimal(0)
  );
  
  // 跳转到订单确认页面
  const handleCheckout = () => {
    if (cartItems.length === 0) return;
    
    // 将购物车商品信息传递到订单确认页面
    navigate("/mall/order-confirm", { 
      state: { skuIds: cartItems.map(item => item.skuId) } 
    });
  };
  
  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">购物车</h1>
      
      {cartItems.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-lg text-muted-foreground">购物车是空的</p>
          <Button className="mt-4" onClick={() => navigate("/mall")}>去购物</Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="md:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>购物车商品 ({cartItems.length})</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {cartItems.map(item => (
                    <div key={item.id} className="flex items-center gap-4 py-3 border-b last:border-0">
                      <img src={item.imageUrl} alt="商品图片" className="h-16 w-16 items-center justify-center rounded" />
                      <div className="flex-1">
                        <h3 className="font-medium">{item.name}</h3>
                        <p className="text-sm text-muted-foreground">单价: ¥{new Decimal(item.price).toFixed(2)}</p>
                      </div>

                      <div className="flex-1">
                        <p className="text-sm text-muted-foreground">规格: {item.specs}</p>
                      </div>
                      
                      <div className="flex items-center gap-2">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => updateQuantity(item.id, item.quantity - 1)}
                        >
                          <MinusCircle className="h-4 w-4" />
                        </Button>
                        <span className="w-8 text-center">{item.quantity}</span>
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => updateQuantity(item.id, item.quantity + 1)}
                        >
                          <PlusCircle className="h-4 w-4" />
                        </Button>
                      </div>
                      
                      <div className="w-20 text-right font-medium">
                        ¥{new Decimal(item.price).mul(item.quantity).toFixed(2)}
                      </div>
                      
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => removeItem(item.id)}
                        className="text-destructive"
                      >
                        <Trash className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
          
          <div>
            <Card>
              <CardHeader>
                <CardTitle>订单摘要</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span>商品总价</span>
                    <span>¥{totalPrice.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>运费</span>
                    <span>¥0.00</span>
                  </div>
                  <div className="border-t pt-2 mt-2 font-bold flex justify-between">
                    <span>总计</span>
                    <span>¥{totalPrice.toFixed(2)}</span>
                  </div>
                </div>
              </CardContent>
              <CardFooter>
                <Button className="w-full" onClick={handleCheckout}>结算</Button>
              </CardFooter>
            </Card>
          </div>
        </div>
      )}
    </div>
  );
}